<?php

use GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 */
class Events
{
    /**
     * 当客户端连接时触发 $client_id键 客服ID值
     */
    public static $yk_kf_id = [];

    /**
     * @var array
     * 记录登录的客服在线情况，便于分组统计
     */
    public static $kf_ids = [] ;

    /**
     * 当客户端连接时触发
     */
    public static function onConnect($client_id)
    {

    }

    /**
     * 当客户端发来消息时触发
     */
    public static function onMessage($client_id, $message)
    {
        global $db;
        $text_type = 'text';
        $message   = json_decode($message, true);
        $types     = explode('-', $message['type']);
        $type      = $types[0];
        if (!empty($types[1])) {
            $text_type = $types[1];
        }

        switch ($type) {
            // 客服登录
            case 'kefu_login':
                // 用户和连接绑定
                Gateway::bindUid($client_id, $message['fromid']);
                Gateway::joinGroup($client_id, $message['fromid']);
                self::$kf_ids[$client_id] = $message['fromid'];

                break;
            // 会员登录
            case 'member_login':
                //记录一下id
                Gateway::bindUid($client_id,$message['fromid']);
                Gateway::joinGroup($client_id,$message['toid']);
                Gateway::leaveGroup($client_id,$message['ofromid']);

                self::$yk_kf_id[$client_id][0] = $message['toid'];
                self::$yk_kf_id[$client_id][1] = $message['fromid'];

                $online_list = Gateway::getUidListByGroup($message['toid']);
                unset($online_list[$message['toid']]);

                $kf_client_id = Gateway::getClientIdByUid($message['toid']);
                if( !empty($kf_client_id) ){
                    Gateway::sendToAll(json_encode([
                        'type'=>'offline',
                        'data'=>$message['ofromid'],
                    ]),$kf_client_id);
                }

                Gateway::sendToUid($message['toid'],json_encode([
                    'type' => 'youke_onopen',
                    'data' => array_values($online_list)
                ]));
                break;
            // 游客登录
            case 'youke_login':
                // 用户和连接绑定
                Gateway::bindUid($client_id, $message['fromid']);
                Gateway::joinGroup($client_id, $message['toid']);
                self::$yk_kf_id[$client_id][0] = $message['toid'];
                self::$yk_kf_id[$client_id][1] = $message['fromid'];
                $online_list = Gateway::getUidListByGroup($message['toid']);
                unset($online_list[$message['toid']]);
                Gateway::sendToUid($message['toid'],json_encode([
                    'type' => 'youke_onopen',
                    'data' => array_values($online_list)
                ]));
            case 'ping':
                break;
            // 聊天
            case 'say':
                $fromid = $message['from_id'];
                $toid   = $message['to_id'];
                $online_list = [];
                // 如果是游客跟客服聊天
                if ($message['utype'] == 'say_from') {
                    // 客服ID
                    $kfId = $toid;
                    // 添加到客服的对话列表里
                    $is_logue = $db->select('vsid')->from('we_im_dialogue')
                        ->where('vsid=' . $fromid . ' and cuid=' . $toid)->row();
                    // 判断内容类型
                    if ($message['type'] == 'say-file') {
                        $new_cont = '[文件]';
                    } elseif ($message['type'] == 'say-img') {
                        $new_cont = '[图片]';
                    } elseif ($message['type'] == 'say-audio') {
                        $new_cont = '[语音]';
                    } else {
                        $content = strip_tags($message['data']);
                        if (strpos($message['data'], 'href')) {
                            $new_cont = '[超链接]';
                        } elseif (strpos($message['data'], 'uploads') || strpos($message['data'], '<img')) {
                            $new_cont = '[图片]';
                        } elseif (preg_match("/emoji/", $message['data'])) {
                            $new_cont = '[表情]';
                        } elseif (strlen($content) > 30) {
                            $new_cont = substr($content, 0, 30);
                        } else {
                            $new_cont = $content;
                        }
                    }
                    if (empty($is_logue)) {
                        $db->insert('we_im_dialogue')->cols([
                            'vsid'     => $fromid,
                            'add_time' => time(),
                            'isshow'   => 1,
                            'new_cont' => $new_cont,
                            'cuid'     => $toid
                        ])->query();
                    } else {
                        try{
                            $db->update('we_im_dialogue')
                                ->cols(['new_cont' => $new_cont, 'add_time' => time()])
                                ->where("vsid={$fromid} AND cuid={$toid}")->query();

                            $db->update('we_im_visitors')
                                ->cols(['is_act' => 1])
                                ->where("is_act = '0' AND id={$fromid}")->query();

                        }catch (\Throwable $e){

                        }

                    }
                    // 给客服推送一个在线列表
                    $online_list = Gateway::getUidListByGroup($toid);
                    unset($online_list[$toid]);

                } else {
                    // 客服ID
                    $kfId = $fromid;
                }

                // 查询主客服
                $cust = $db->select('id,pid,is_main')->from('we_im_customer')
                    ->where("id={$kfId}")->row();
                if (!empty($cust)) {
                    // 把信息存到数据库
                    $data = [
                        'type'           => $text_type,
                        'utype'          => $message['utype'],
                        'send'           => $fromid,
                        'send_nick'      => $message['from_nick'],
                        'send_avatar'    => $message['from_avatar'],
                        'receive'        => $toid,
                        'receive_nick'   => $message['to_nick'],
                        'receive_avatar' => $message['to_avatar'],
                        'content'        => $message['data'],
                        'send_time'      => time(),
                        'main_id'        => $cust['is_main'] == 0 ? $cust['pid'] : $cust['id'],
                        'source_cuid'    => $kfId,
                    ];
                    $db->insert('we_im_record')->cols($data)->query();
                }

                $client = Gateway::getClientIdByUid($toid);
                if (!empty($client)) {
                    $data['online_list'] = array_values($online_list);
                    Gateway::sendToUid($toid, json_encode([
                        'type' => $type,
                        'data' => $data
                    ]));
                } else {
                    // 提示发送方没有在线
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'no_online'
                    ]));
                }
                break;
            // 关闭
            case 'close_user':
                // toid 代表的是游客ID

                break;
            // 转接
            case 'transfer':
                // 获取转接给某个$client_id游客
                $zj_client_id = Gateway::getClientIdByUid($message['yk_id']);
                if (!empty($zj_client_id[0])) {
                    // 进入新的分组
                    Gateway::joinGroup($zj_client_id[0], $message['zj_kf_id']);
                    // 踢出原始群组
                    Gateway::leaveGroup($zj_client_id[0], $message['ys_kf_id']);
                    // 给游客发送一个提示
                    Gateway::sendToClient($zj_client_id[0], json_encode([
                        'type' => 'zj_yk_online',
                        'data' => [
                            'kf_id'     => $message['zj_kf_id'],
                            'kf_nick'   => $message['zj_kf_name'],
                            'kf_avatar' => $message['zj_kf_avatar']
                        ]
                    ]));
                    // 给新客服说一声
                    $online_list = Gateway::getUidListByGroup($message['zj_kf_id']);
                    unset($online_list[$message['zj_kf_id']]);
                    $data['online_list'] = array_values($online_list);
                    Gateway::sendToUid($message['zj_kf_id'], json_encode([
                        'type' => 'refresh_chat_list',
                        'data' => $data
                    ]));

                }
                break;
        }
    }

    /**
     * 当用户断开连接时触发
     */
    public static function onClose($client_id)
    {
        if( !empty( self::$kf_ids[$client_id] ) ){
            unset(self::$kf_ids[$client_id]) ;
        }

        if (!empty(self::$yk_kf_id[$client_id])) {

            $kfId = self::$yk_kf_id[$client_id][0];
            $ykId = self::$yk_kf_id[$client_id][1];
            $kf_client_id = Gateway::getClientIdByUid($kfId);
            if (!empty($kf_client_id)) {
                // 通知客服离线
                Gateway::sendToAll(json_encode([
                    'type' => 'offline',
                    'data' => $ykId
                ]), $kf_client_id);
            }
            unset(self::$yk_kf_id[$client_id]);
        }
    }
}
